package com.forever7776.life.core.service.impl.sys;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.forever7776.life.core.common.util.ResultVoUtil;
import com.forever7776.life.core.entity.sys.SysRole;
import com.forever7776.life.core.entity.sys.SysRoleUser;
import com.forever7776.life.core.mapper.sys.SysRoleMapper;
import com.forever7776.life.core.service.sys.ISysRoleService;
import com.forever7776.life.core.service.sys.ISysRoleUserService;
import com.forever7776.life.remote.common.vo.ResultVO;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author kz
 * @since 2018-01-18
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

    @Autowired
    private ISysRoleUserService sysRoleUserService;

    /**
     * 删除角色
     *
     * @param id
     * @return
     */
    @Override
    public ResultVO delete(String id) {
        List<SysRoleUser> roleUsers = sysRoleUserService.selectList(new EntityWrapper<SysRoleUser>().eq("role_id", id));
        if (CollectionUtils.isNotEmpty(roleUsers)) {
            return ResultVoUtil.getFailResult("该角色下有用户，不允许删除！");
        }
        this.deleteById(id);
        return ResultVoUtil.getSuccessResult("删除成功！");
    }

    /**
     * 修改角色状态
     *
     * @param id
     * @param status
     * @return
     */
    @Override
    public ResultVO frozen(String id, Integer status) {
        SysRole role = selectById(id);
        if (role == null) {
            return ResultVoUtil.getFailResult("该角色不存在！");
        }
        role.setStatus(status);
        this.updateById(role);
        return ResultVoUtil.getSuccessResult("操作成功！");
    }

    /**
     * 查询角色列表
     *
     * @param page
     * @param roleName
     * @return
     */
    @Override
    public Page<SysRole> selectAll(Page<SysRole> page, String roleName) {
        return selectPage(page, new EntityWrapper<SysRole>().like("role_name", roleName).orderBy("last_update", false));
    }
}
